using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using ThridGroup.ERP.Application.Contracts.OrderManagement;
using ThridGroup.ERP.DTO.OrderManagement;
using System.Text;
using System.Text.Json;

namespace ThridGroup.ERP.Web.Areas.OrderManagement.Controllers
{
    [Area("OrderManagement")]
    [Route("OrderManagement/[controller]")]
    public class SalesOrderController : AbpController
    {
        private readonly ISalesOrderService _salesOrderService;
        private readonly ILogger<SalesOrderController> _logger;

        public SalesOrderController(
            ISalesOrderService salesOrderService,
            ILogger<SalesOrderController> logger)
        {
            _salesOrderService = salesOrderService;
            _logger = logger;
        }

        /// <summary>
        /// 销售订单首页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("")]
        [Route("Index")]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 编辑页面
        /// </summary>
        /// <param name="id">销售订单ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("Edit")]
        public async Task<IActionResult> Edit(int? id)
        {
            try
            {
                if (id.HasValue && id.Value > 0)
                {
                    var model = await _salesOrderService.GetSalesOrder(id.Value);
                    return View(model);
                }

                // 默认创建日期为当天
                return View(new SalesOrderDto { DOrderDate = DateTime.Now });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"加载编辑页面失败：{ex.Message}");
                return View("Error", ex.Message);
            }
        }

        /// <summary>
        /// 获取销售订单列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetSalesOrders")]
        public async Task<IActionResult> GetSalesOrders(
            string orderCode = null,
            string orderName = null,
            string customerCode = null,
            string customerName = null,
            string customerPONumber = null,
            string orderCategory = null,
            string orderType = null,
            string orderFollower = null,
            string salesperson = null,
            string qualityRequirement = null,
            string currency = null,
            string settlementMethod = null,
            string orderDateStart = null,
            string orderDateEnd = null,
            string deliveryDateStart = null,
            string deliveryDateEnd = null,
            int page = 1,
            int limit = 10)
        {
            try
            {
                _logger.LogInformation($"接收到获取销售订单列表请求：orderCode={orderCode}, orderName={orderName}, customerCode={customerCode}, customerName={customerName}, customerPONumber={customerPONumber}, orderCategory={orderCategory}, orderType={orderType}, orderFollower={orderFollower}, salesperson={salesperson}, qualityRequirement={qualityRequirement}, currency={currency}, settlementMethod={settlementMethod}, orderDateStart={orderDateStart}, orderDateEnd={orderDateEnd}, deliveryDateStart={deliveryDateStart}, deliveryDateEnd={deliveryDateEnd}, page={page}, limit={limit}");

                List<SalesOrderDto> allData;
                try
                {
                    allData = await _salesOrderService.GetSalesOrdersByCondition(
                        orderCode,
                        orderName,
                        customerCode,
                        customerName,
                        customerPONumber,
                        orderCategory,
                        orderType,
                        orderFollower,
                        salesperson,
                        qualityRequirement,
                        currency,
                        settlementMethod,
                        orderDateStart,
                        orderDateEnd,
                        deliveryDateStart,
                        deliveryDateEnd
                    );
                }
                catch (Exception serviceEx)
                {
                    _logger.LogError(serviceEx, $"服务层获取销售订单数据失败：{serviceEx.Message}");
                    return Json(new { code = 1, msg = "获取数据失败：" + serviceEx.Message, count = 0, data = new List<SalesOrderDto>() });
                }

                if (allData == null || !allData.Any())
                {
                    _logger.LogInformation("获取销售订单列表成功，但无数据");
                    return Json(new { code = 0, msg = "获取成功，但无数据", count = 0, data = new List<SalesOrderDto>() });
                }

                var totalCount = allData.Count;
                var pageData = allData
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToList();

                _logger.LogInformation($"获取销售订单列表成功，总数：{totalCount}，当前页数据量：{pageData.Count}");
                return Json(new { code = 0, msg = "获取成功", count = totalCount, data = pageData });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取销售订单列表失败：{ex.Message}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, count = 0, data = new List<SalesOrderDto>() });
            }
        }

        /// <summary>
        /// 获取单个销售订单
        /// </summary>
        /// <param name="id">销售订单ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetById/{id}")]
        public async Task<IActionResult> GetSalesOrder(int id)
        {
            try
            {
                _logger.LogInformation($"接收到获取单个销售订单请求，ID：{id}");

                if (id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的销售订单ID", data = new object() });
                }

                var model = await _salesOrderService.GetSalesOrder(id);
                if (model == null)
                {
                    return Json(new { code = 1, msg = $"未找到ID为{id}的销售订单", data = new object() });
                }

                _logger.LogInformation($"成功获取销售订单，ID：{id}");
                _logger.LogInformation($"订单基本信息：OrderCode={model.DOrderCode}, CustomerName={model.DCustomerName}");
                _logger.LogInformation($"备注字段内容：{model.DRemarks}");
                _logger.LogInformation($"产品明细数量：{model.Products?.Count ?? 0}");

                // 如果有产品明细，记录详细信息
                if (model.Products != null && model.Products.Count > 0)
                {
                    _logger.LogInformation("产品明细列表：");
                    for (int i = 0; i < model.Products.Count; i++)
                    {
                        var product = model.Products[i];
                        _logger.LogInformation($"  [{i + 1}] 编码:{product.ProductCode}, 名称:{product.ProductName}, 数量:{product.Quantity}, 单价:{product.Price}");
                    }
                }

                var result = new
                {
                    code = 0,
                    msg = "获取成功",
                    data = new
                    {
                        model.Id,
                        model.DOrderCode,
                        model.DOrderName,
                        model.DCustomerCode,
                        model.DCustomerName,
                        model.DCustomerPONumber,
                        model.DOrderDate,
                        model.DeliveryDate,
                        model.DCurrency,
                        model.DSettlementMethod,
                        model.DOrderCategory,
                        model.DOrderFollower,
                        model.DSalesperson,
                        model.DQualityRequirement,
                        model.DRemarks,
                        products = model.Products ?? new List<SalesOrderProductDto>()
                    }
                };

                _logger.LogInformation($"返回数据包含 {model.Products?.Count ?? 0} 条产品明细");

                // 记录返回给前端的完整数据结构
                _logger.LogInformation($"返回给前端的JSON数据：{Newtonsoft.Json.JsonConvert.SerializeObject(result)}");

                return Json(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取单个销售订单失败，ID：{id}，错误：{ex.Message}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, data = new object() });
            }
        }

        /// <summary>
        /// 添加销售订单
        /// </summary>
        /// <param name="input">销售订单数据</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Add")]
        public async Task<IActionResult> Add([FromBody] CreateUpdateSalesOrderDto input)
        {
            try
            {
                _logger.LogInformation($"接收到添加销售订单请求：OrderCode={input?.DOrderCode}, OrderName={input?.DOrderName}");

                if (input == null)
                {
                    return Json(new { code = 1, msg = "无效的销售订单数据" });
                }

                // 记录完整的输入数据，帮助调试
                _logger.LogInformation($"销售订单输入数据: {Newtonsoft.Json.JsonConvert.SerializeObject(input)}");

                // 处理产品明细数据 - 在调用服务之前处理
                if (input.Products != null && input.Products.Count > 0)
                {
                    _logger.LogInformation($"销售订单 {input.DOrderCode} 包含 {input.Products.Count} 个产品明细项");
                    foreach (var product in input.Products)
                    {
                        _logger.LogInformation($"产品明细: 编码={product.ProductCode}, 名称={product.ProductName}, " +
                            $"数量={product.Quantity}, 单位={product.Unit}, 单价={product.Price}, 金额={product.Amount}");
                    }

                    // 将产品明细数据序列化为JSON并存储在备注字段中
                    try
                    {
                        var settings = new Newtonsoft.Json.JsonSerializerSettings
                        {
                            NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                            Formatting = Newtonsoft.Json.Formatting.None
                        };

                        string productJson = Newtonsoft.Json.JsonConvert.SerializeObject(input.Products, settings);
                        _logger.LogInformation($"序列化的产品明细JSON: {productJson}");

                        string originalRemarks = input.DRemarks ?? "";

                        // 移除旧的产品明细数据（如果有）
                        const string productPrefix = "||PRODUCTS:";
                        int productIndex = originalRemarks.IndexOf(productPrefix);
                        if (productIndex >= 0)
                        {
                            originalRemarks = originalRemarks.Substring(0, productIndex).TrimEnd();
                        }

                        // 添加新的产品明细数据，确保格式正确
                        input.DRemarks = originalRemarks + productPrefix + productJson;

                        _logger.LogInformation($"最终的备注字段内容: {input.DRemarks}");
                    }
                    catch (Exception jsonEx)
                    {
                        _logger.LogError(jsonEx, $"序列化产品明细数据失败: {jsonEx.Message}");
                        throw new Exception("保存产品明细数据失败：" + jsonEx.Message);
                    }
                }
                else
                {
                    _logger.LogWarning($"销售订单 {input.DOrderCode} 没有包含产品明细项");
                }

                // 保存销售订单基本信息
                var id = await _salesOrderService.AddSalesOrder(input);

                return Json(new { code = 0, msg = "添加成功", id = id });
            }
            catch (ArgumentException argEx)
            {
                _logger.LogWarning(argEx, $"添加销售订单参数验证失败：{argEx.Message}");
                return Json(new { code = 1, msg = argEx.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加销售订单失败：{ex.Message}");
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 更新销售订单
        /// </summary>
        /// <param name="input">销售订单数据</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Update")]
        public async Task<IActionResult> Update([FromBody] SalesOrderDto input)
        {
            try
            {
                _logger.LogInformation($"接收到更新销售订单请求：ID={input?.Id}, OrderCode={input?.DOrderCode}, OrderName={input?.DOrderName}");

                if (input == null || input.Id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的销售订单数据或ID" });
                }

                // 处理产品明细数据 - 在调用服务之前处理
                if (input.Products != null && input.Products.Count > 0)
                {
                    _logger.LogInformation($"更新销售订单 {input.DOrderCode} 包含 {input.Products.Count} 个产品明细项");
                    foreach (var product in input.Products)
                    {
                        _logger.LogInformation($"产品明细: 编码={product.ProductCode}, 名称={product.ProductName}, " +
                            $"数量={product.Quantity}, 单位={product.Unit}, 单价={product.Price}, 金额={product.Amount}");
                    }

                    // 将产品明细数据序列化为JSON并存储在备注字段中
                    try
                    {
                        var settings = new Newtonsoft.Json.JsonSerializerSettings
                        {
                            NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                            Formatting = Newtonsoft.Json.Formatting.None
                        };

                        string productJson = Newtonsoft.Json.JsonConvert.SerializeObject(input.Products, settings);
                        _logger.LogInformation($"序列化的产品明细JSON: {productJson}");

                        string originalRemarks = input.DRemarks ?? "";

                        // 移除旧的产品明细数据（如果有）
                        const string productPrefix = "||PRODUCTS:";
                        int productIndex = originalRemarks.IndexOf(productPrefix);
                        if (productIndex >= 0)
                        {
                            originalRemarks = originalRemarks.Substring(0, productIndex).TrimEnd();
                        }

                        // 添加新的产品明细数据，确保格式正确
                        input.DRemarks = originalRemarks + productPrefix + productJson;

                        _logger.LogInformation($"最终的备注字段内容: {input.DRemarks}");
                    }
                    catch (Exception jsonEx)
                    {
                        _logger.LogError(jsonEx, $"序列化产品明细数据失败: {jsonEx.Message}");
                        throw new Exception("保存产品明细数据失败：" + jsonEx.Message);
                    }
                }

                // 转换为创建更新DTO
                var updateDto = new CreateUpdateSalesOrderDto
                {
                    DOrderCode = input.DOrderCode,
                    DOrderName = input.DOrderName,
                    DCustomerCode = input.DCustomerCode,
                    DCustomerName = input.DCustomerName,
                    DCustomerPONumber = input.DCustomerPONumber,
                    DOrderDate = input.DOrderDate,
                    DeliveryDate = input.DeliveryDate,
                    DCurrency = input.DCurrency,
                    DSettlementMethod = input.DSettlementMethod,
                    DOrderCategory = input.DOrderCategory,
                    DOrderFollower = input.DOrderFollower,
                    DSalesperson = input.DSalesperson,
                    DQualityRequirement = input.DQualityRequirement,
                    DRemarks = input.DRemarks,
                    Products = input.Products
                };

                var id = await _salesOrderService.UpdateSalesOrder(input.Id, updateDto);
                return Json(new { code = 0, msg = "更新成功", id = id });
            }
            catch (ArgumentException argEx)
            {
                _logger.LogWarning(argEx, $"更新销售订单参数验证失败：{argEx.Message}");
                return Json(new { code = 1, msg = argEx.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新销售订单失败：{ex.Message}");
                return Json(new { code = 1, msg = "更新失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 删除销售订单
        /// </summary>
        /// <param name="id">销售订单ID</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Delete/{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                _logger.LogInformation($"接收到删除销售订单请求，ID：{id}");

                if (id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的销售订单ID" });
                }

                await _salesOrderService.DeleteSalesOrder(id);
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除销售订单失败，ID：{id}，错误：{ex.Message}");
                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 检查销售订单编码是否存在
        /// </summary>
        /// <param name="orderCode">订单编码</param>
        /// <param name="id">排除的订单ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("CheckOrderCode")]
        public async Task<IActionResult> CheckOrderCode(string orderCode, int? id = null)
        {
            try
            {
                if (string.IsNullOrEmpty(orderCode))
                {
                    return Json(new { exists = false });
                }

                var exists = await _salesOrderService.IsOrderCodeExist(orderCode, id);
                return Json(new { exists });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"检查销售订单编码是否存在失败，OrderCode：{orderCode}，错误：{ex.Message}");
                return Json(new { exists = false, error = ex.Message });
            }
        }

        /// <summary>
        /// 批量删除销售订单
        /// </summary>
        /// <param name="ids">订单ID列表</param>
        /// <returns></returns>
        [HttpPost]
        [Route("BatchDelete")]
        public async Task<IActionResult> BatchDelete([FromBody] List<int> ids)
        {
            try
            {
                _logger.LogInformation($"接收到批量删除请求，订单数量：{ids?.Count}");

                if (ids == null || ids.Count == 0)
                {
                    return Json(new { code = 1, msg = "请选择要删除的订单" });
                }

                int successCount = 0;
                List<string> errorMessages = new List<string>();

                foreach (int id in ids)
                {
                    try
                    {
                        await _salesOrderService.DeleteSalesOrder(id);
                        successCount++;
                    }
                    catch (Exception ex)
                    {
                        errorMessages.Add($"ID {id}: {ex.Message}");
                        _logger.LogError(ex, $"批量删除销售订单失败，ID：{id}，错误：{ex.Message}");
                    }
                }

                if (successCount == ids.Count)
                {
                    return Json(new { code = 0, msg = $"成功删除 {successCount} 条订单" });
                }
                else if (successCount > 0)
                {
                    return Json(new { code = 0, msg = $"部分删除成功，共 {successCount}/{ids.Count} 条，失败原因：{string.Join("; ", errorMessages)}" });
                }
                else
                {
                    return Json(new { code = 1, msg = $"删除失败：{string.Join("; ", errorMessages)}" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"批量删除销售订单失败：{ex.Message}");
                return Json(new { code = 1, msg = "批量删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 导出销售订单数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("Export")]
        public async Task<IActionResult> Export(string orderCode = null, string orderName = null, string customerCode = null,
            string customerName = null, string orderCategory = null, string customerPONumber = null)
        {
            try
            {
                _logger.LogInformation("接收到导出销售订单请求");

                // 根据条件获取数据
                List<SalesOrderDto> data;

                // 如果有查询条件，使用条件查询
                if (!string.IsNullOrEmpty(orderCode) || !string.IsNullOrEmpty(customerName) || !string.IsNullOrEmpty(orderCategory))
                {
                    data = await _salesOrderService.GetSalesOrdersByCondition(orderCode,
                                                                              null,           // orderName
                                                                              null,           // customerCode
                                                                              customerName,
                                                                              null,           // customerPONumber
                                                                              orderCategory,
                                                                              null,           // orderType
                                                                              null,           // orderFollower
                                                                              null,           // salesperson
                                                                              null,           // qualityRequirement
                                                                              null,           // currency
                                                                              null,           // settlementMethod
                                                                              null,           // orderDateStart
                                                                              null,           // orderDateEnd
                                                                              null,           // deliveryDateStart
                                                                              null);            // deliveryDateEnd);
                }
                else
                {
                    // 否则获取全部数据
                    data = await _salesOrderService.GetSalesOrders();
                }

                // 返回CSV格式的数据
                var csv = GenerateCSV(data);
                var bytes = System.Text.Encoding.UTF8.GetBytes(csv);

                // 返回文件
                return File(bytes, "text/csv", $"销售订单导出_{DateTime.Now:yyyyMMdd_HHmmss}.csv");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"导出销售订单数据失败：{ex.Message}");
                return Json(new { code = 1, msg = "导出失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 生成CSV数据
        /// </summary>
        private string GenerateCSV(List<SalesOrderDto> data)
        {
            StringBuilder sb = new StringBuilder();

            // 添加CSV头
            sb.AppendLine("订单编码,订单名称,客户编码,客户名称,客户PO号,订货日期,交货日期,订单类别,跟单,业务员,币别,结账方式,备注");

            // 添加数据行
            foreach (var item in data)
            {
                sb.AppendLine(
                    $"{EscapeCSV(item.DOrderCode)}," +
                    $"{EscapeCSV(item.DOrderName)}," +
                    $"{EscapeCSV(item.DCustomerCode)}," +
                    $"{EscapeCSV(item.DCustomerName)}," +
                    $"{EscapeCSV(item.DCustomerPONumber)}," +
                    $"{item.DOrderDate:yyyy-MM-dd}," +
                    $"{EscapeCSV(item.DeliveryDate)}," +
                    $"{EscapeCSV(item.DOrderCategory)}," +
                    $"{EscapeCSV(item.DOrderFollower)}," +
                    $"{EscapeCSV(item.DSalesperson)}," +
                    $"{EscapeCSV(item.DCurrency)}," +
                    $"{EscapeCSV(item.DSettlementMethod)}," +
                    $"{EscapeCSV(item.DRemarks)}"
                );
            }

            return sb.ToString();
        }

        /// <summary>
        /// CSV特殊字符处理
        /// </summary>
        private string EscapeCSV(string value)
        {
            if (string.IsNullOrEmpty(value)) return "";

            if (value.Contains(",") || value.Contains("\"") || value.Contains("\n"))
            {
                // 如有特殊字符，加双引号并将双引号转义
                return "\"" + value.Replace("\"", "\"\"") + "\"";
            }

            return value;
        }

        /// <summary>
        /// 获取销售订单的产品明细
        /// </summary>
        /// <param name="id">销售订单ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetProductDetails/{id}")]
        public async Task<IActionResult> GetProductDetails(int id)
        {
            try
            {
                _logger.LogInformation($"接收到获取销售订单产品明细请求，ID：{id}");

                if (id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的销售订单ID", data = new List<SalesOrderProductDto>() });
                }

                // 从数据库获取真实的销售订单数据
                var salesOrder = await _salesOrderService.GetSalesOrder(id);
                if (salesOrder == null)
                {
                    return Json(new { code = 1, msg = "未找到对应的销售订单", data = new List<SalesOrderProductDto>() });
                }

                // 从备注字段中解析产品明细数据
                var productDetails = ExtractProductDetailsFromRemarks(salesOrder.DRemarks);

                _logger.LogInformation($"成功获取产品明细数据，共 {productDetails.Count} 条");
                return Json(new { code = 0, msg = "获取成功", data = productDetails });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取销售订单产品明细失败，ID：{id}，错误：{ex.Message}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, data = new List<SalesOrderProductDto>() });
            }
        }

        /// <summary>
        /// 从备注字段中提取产品明细数据
        /// </summary>
        /// <param name="remarks">备注字段内容</param>
        /// <returns></returns>
        private List<SalesOrderProductDto> ExtractProductDetailsFromRemarks(string remarks)
        {
            var productDetails = new List<SalesOrderProductDto>();

            try
            {
                if (string.IsNullOrEmpty(remarks))
                {
                    _logger.LogInformation("备注字段为空，无法提取产品明细数据");
                    return productDetails;
                }

                _logger.LogInformation($"开始从备注字段提取产品明细数据，原始备注内容：{remarks}");

                // 查找产品明细JSON数据
                const string productPrefix = "||PRODUCTS:";
                int productIndex = remarks.IndexOf(productPrefix);

                if (productIndex >= 0)
                {
                    // 提取JSON部分并清理可能的空白字符
                    string jsonData = remarks.Substring(productIndex + productPrefix.Length).Trim();
                    _logger.LogInformation($"提取到的原始JSON数据：{jsonData}");

                    // 确保JSON数据是一个有效的数组格式
                    if (!jsonData.StartsWith("["))
                    {
                        jsonData = "[" + jsonData;
                    }
                    if (!jsonData.EndsWith("]"))
                    {
                        jsonData = jsonData + "]";
                    }

                    _logger.LogInformation($"处理后的JSON数据：{jsonData}");

                    // 首先尝试使用Newtonsoft.Json解析
                    try
                    {
                        var settings = new Newtonsoft.Json.JsonSerializerSettings
                        {
                            NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                            MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
                        };

                        var products = Newtonsoft.Json.JsonConvert.DeserializeObject<List<SalesOrderProductDto>>(jsonData, settings);

                        if (products != null && products.Count > 0)
                        {
                            productDetails = products;
                            _logger.LogInformation($"成功使用Newtonsoft.Json从备注字段解析出 {productDetails.Count} 条产品明细");
                            return productDetails;
                        }
                    }
                    catch (Exception newtonsoftEx)
                    {
                        _logger.LogError(newtonsoftEx, $"Newtonsoft.Json反序列化失败：{newtonsoftEx.Message}");

                        // 如果失败，尝试清理JSON数据中的特殊字符
                        try
                        {
                            jsonData = jsonData.Replace("\r", "").Replace("\n", "").Replace("\t", "").Trim();
                            var products = Newtonsoft.Json.JsonConvert.DeserializeObject<List<SalesOrderProductDto>>(jsonData);

                            if (products != null && products.Count > 0)
                            {
                                productDetails = products;
                                _logger.LogInformation($"清理特殊字符后成功解析出 {productDetails.Count} 条产品明细");
                                return productDetails;
                            }
                        }
                        catch (Exception cleanEx)
                        {
                            _logger.LogError(cleanEx, $"清理特殊字符后解析仍然失败：{cleanEx.Message}");
                        }
                    }

                    // 如果Newtonsoft.Json失败，尝试使用System.Text.Json
                    try
                    {
                        var options = new JsonSerializerOptions
                        {
                            PropertyNameCaseInsensitive = true,
                            AllowTrailingCommas = true,
                            ReadCommentHandling = JsonCommentHandling.Skip
                        };

                        var products = System.Text.Json.JsonSerializer.Deserialize<List<SalesOrderProductDto>>(jsonData, options);

                        if (products != null && products.Count > 0)
                        {
                            productDetails = products;
                            _logger.LogInformation($"成功使用System.Text.Json从备注字段解析出 {productDetails.Count} 条产品明细");
                            return productDetails;
                        }
                    }
                    catch (Exception systemJsonEx)
                    {
                        _logger.LogError(systemJsonEx, $"System.Text.Json反序列化失败：{systemJsonEx.Message}");
                    }

                    _logger.LogWarning("所有JSON解析方法都失败，无法提取产品明细数据");
                }
                else
                {
                    _logger.LogInformation($"备注字段中未找到产品明细数据标识'{productPrefix}'");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"解析产品明细数据失败：{ex.Message}");
            }

            return productDetails;
        }
    }
}